//
//  CZStatusViewModel.swift
//  sinaWeiboswift
//
//  Created by 段文杰 on 16/4/13.
//  Copyright © 2016年 段文杰. All rights reserved.
//

import UIKit
import SDWebImage
class CZStatusViewModel: NSObject {
    // 单例
    static let sharedInstance: CZStatusViewModel = CZStatusViewModel()
    
    /// 加载微博数据
    
    func loadStatus(loadStatusCallback: (statuses: [CZStatusModel]?, error: NSError?)-> ()) {
        // 1.urlString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 2.参数
        let parameters = ["access_token": CZUseraccountViewModel.sharInatance.userAccount!.access_token!]


        CZNetWorkingTool.sharInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
//        HMPrint("获取微博数据成功了: \(responseObject)")
            // 获取微博数据
            if let dict = responseObject as? [String: AnyObject], let statusesDict = dict["statuses"] as? [[String: AnyObject]] {
                
                // 定义数组来保存转好的微博模型
                //                var statusModels = [HMStatus]()
                var statusModels: [CZStatusModel] = []
                
                // 遍历每个字典
                for dict in statusesDict {
                    // 字典转模型
                    let status = CZStatusModel(dict: dict)
                    
                    // 将模型添加到数组里面
                    statusModels.append(status)
                    
                    //缓存图片
                    cacheWebImage(statusModels, loadStatusCallback: loadStatusCallback)
                    
                }
                loadStatusCallback(statuses: statusModels, error: nil)
            }

            }) { (task, error) in
                
                
                

                HMPrint("获取微博数据失败了\(error)")
        }
    }
}


//缓存webView图片
func cacheWebImage(statuses: [CZStatusModel],loadStatusCallback: (statuses: [CZStatusModel]?, error: NSError?)-> ()){

    //创建任务组
    let group = dispatch_group_create()
    
    //判断有没有任务下载
    var downloadURL : [NSURL]?
    
    for status in statuses {
        //微博模型有没有下载的
        downloadURL = status.storePicutreURLs
        if downloadURL == nil {
            
            //转发微博有没有下载的
            downloadURL = status.retweeted_status?.storePicutreURLs
            
            
        }
        
        if downloadURL == nil {
            return
        }else{
        
        //这里就是真正的有值了
            if let url = downloadURL {
                
                //一张图片
                if url.count == 1 {
                    let url1 = url.first
                
                    //进入组
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url1, options: [], progress: { (_, _) in
                        
                        }, completed: { (image, error, _, _, _) in
                            dispatch_group_leave(group)

                            if error != nil {
//                            HMPrint("数据获取出错\(error)")
                            return
                            }else{
//                            HMPrint("数据获取成功\(image)")
          
                                
                            }
//                            HMPrint("tp下载完成")
                    })
                
                }
            }
        
        }
        
    }
    
    //监听图片下载完成没有
    
    dispatch_group_notify(group, dispatch_get_main_queue()) { 
    
        HMPrint("所有的图片下载完成")
        
        //会主线程更新
        loadStatusCallback(statuses: statuses, error: nil)
        
    }
 
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    



}

